<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            display: flex;
            flex-direction: column;
            height: 100vh;
            background-color: #f5f5f5;
        }
        
        .header {
            background-color: #2c3e50;
            color: white;
            padding: 1rem 2rem;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1000px;
            margin: 0 auto;
            width: 100%;
            padding: 1rem;
            overflow: hidden;
        }
        
        .chat-box {
            flex: 1;
            background-color: white;
            border-radius: 10px;
            padding: 1rem;
            overflow-y: auto;
            margin-bottom: 1rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .message {
            margin-bottom: 1rem;
            padding: 0.8rem 1rem;
            border-radius: 1rem;
            max-width: 80%;
            word-wrap: break-word;
        }
        
        .user-message {
            background-color: #e3f2fd;
            margin-left: auto;
            border-bottom-right-radius: 0.2rem;
        }
        
        .assistant-message {
            background-color: #f1f1f1;
            margin-right: auto;
            border-bottom-left-radius: 0.2rem;
        }
        
        .thinking {
            color: #666;
            font-style: italic;
            margin-bottom: 1rem;
            display: none;
        }
        
        .input-area {
            display: flex;
            gap: 0.5rem;
        }
        
        .message-input {
            flex: 1;
            padding: 0.8rem 1rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            resize: none;
            height: 60px;
        }
        
        .send-button {
            padding: 0 1.5rem;
            background-color: #2c3e50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        
        .send-button:hover {
            background-color: #1e2b38;
        }
        
        .send-button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        
        pre {
            background-color: #f8f8f8;
            padding: 0.5rem;
            border-radius: 5px;
            overflow-x: auto;
            margin: 0.5rem 0;
        }
        
        code {
            font-family: Consolas, monospace;
        }
        
        .status {
            font-size: 0.8rem;
            color: #666;
            text-align: center;
            margin-top: 0.5rem;
        }
        
        @media (max-width: 768px) {
            .message {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>AI聊天助手</h1>
    </div>
    
    <div class="chat-container">
        <div class="chat-box" id="chatBox">
            <div class="message assistant-message">
                你好！我是你的助手。有什么我可以帮助你的吗？
            </div>
        </div>
        
        <div class="thinking" id="thinking">思考中...</div>
        
        <div class="input-area">
            <textarea 
                class="message-input" 
                id="messageInput" 
                placeholder="输入您的问题..."
                onkeypress="handleKeyPress(event)"
            ></textarea>
            <button class="send-button" id="sendButton">发送</button>
        </div>
        
        <div class="status" id="status">按下 Esc 键退出程序</div>
    </div>

    <script>
        const chatBox = document.getElementById('chatBox');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const thinkingIndicator = document.getElementById('thinking');
        const statusDisplay = document.getElementById('status');
        
        // 初始化对话历史
        let messages = [
            {"role": "system", "content": "你是一个乐于助人的助手。"}
        ];
        
        // 监听发送按钮点击事件
        sendButton.addEventListener('click', sendMessage);
        
        // 处理键盘事件
        function handleKeyPress(event) {
            // Enter键发送消息（不按Shift）
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
            
            // Esc键退出
            if (event.key === 'Escape') {
                quitApp();
            }
        }
        
        // 监听Esc键
        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape') {
                quitApp();
            }
        });
        
        // 发送消息
        async function sendMessage() {
            const userInput = messageInput.value.trim();
            if (!userInput) return;
            
            // 显示用户消息
            addMessage(userInput, 'user');
            messageInput.value = '';
            
            // 显示思考中...
            thinkingIndicator.style.display = 'block';
            sendButton.disabled = true;
            
            try {
                // 将消息发送到后端API
                const response = await fetch('http://localhost:5000/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        messages: [...messages, {"role": "user", "content": userInput}]
                    })
                });
                
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                
                const data = await response.json();
                const assistantReply = data.reply;
                
                // 更新对话历史
                messages.push({"role": "user", "content": userInput});
                messages.push({"role": "assistant", "content": assistantReply});
                
                // 显示助手回复
                addMessage(assistantReply, 'assistant');
            } catch (error) {
                console.error('出错了:', error);
                addMessage('抱歉，发生了错误：' + error.message, 'assistant');
            } finally {
                // 隐藏思考中...
                thinkingIndicator.style.display = 'none';
                sendButton.disabled = false;
                messageInput.focus();
            }
        }
        
        // 添加消息到聊天框
        function addMessage(content, role) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}-message`;
            
            // 处理代码块，支持Markdown样式的代码
            let formattedContent = content;
            if (content.includes('```')) {
                formattedContent = content.replace(/```(\w*)\n([\s\S]*?)\n```/g, '<pre><code>$2</code></pre>');
            }
            
            messageDiv.innerHTML = formatMessage(formattedContent);
            chatBox.appendChild(messageDiv);
            
            // 自动滚动到底部
            chatBox.scrollTop = chatBox.scrollHeight;
        }
        
        // 简单格式化消息（处理换行和基本Markdown）
        function formatMessage(text) {
            let formatted = text
                // 处理换行
                .replace(/\n/g, '<br>')
                // 处理粗体
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                // 处理斜体
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                // 处理行内代码
                .replace(/`([^`]+)`/g, '<code>$1</code>');
            
            return formatted;
        }
        
        // 退出应用
        function quitApp() {
            statusDisplay.textContent = "正在退出...";
            // 在实际应用中，这里可以发送退出信号到后端
            fetch('http://localhost:5000/quit', { method: 'POST' })
                .then(() => {
                    statusDisplay.textContent = "已安全退出。";
                })
                .catch(() => {
                    // 即使后端退出失败，也显示退出消息
                    statusDisplay.textContent = "已退出。";
                });
        }
    </script>
</body>
</html>